package com.gsi.webstore.platform.storefront.pipelet.orderprocess.basket;

import java.util.Iterator;

import com.intershop.beehive.bts.capi.orderprocess.ProductLineItem;
import com.intershop.beehive.bts.capi.orderprocess.basket.Basket;
import com.intershop.beehive.bts.capi.orderprocess.basket.BasketMgr;
import com.intershop.beehive.core.capi.naming.NamingMgr;
import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.beehive.core.capi.pipeline.PipelineInitializationException;

/**
 * Clears all items from the basket.
 */
public class ClearBasketItems extends Pipelet
{
    BasketMgr basketMgr = null;
    /**
     * Constant used to access the pipeline dictionary with key 'Basket'
     */
    public static final String DN_BASKET = "Basket";

    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as a
     * parameter.
     * 
     * @param dict
     *            The pipeline dictionary to be used.
     * @throws PipeletExecutionException
     *             Thrown in case of severe errors that make the pipelet execute
     *             impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict)
    throws PipeletExecutionException {        
        // lookup 'Basket' in pipeline dictionary
        Basket basket = (Basket)dict.get(DN_BASKET);
        if (null == basket)
        {
            throw new PipeletExecutionException("Mandatory input parameter 'Basket' not available in pipeline dictionary.");
        
        }

        Iterator<ProductLineItem> lineItems = basket.createProductLineItemsIterator();
        while (lineItems.hasNext()) {
            ProductLineItem lineItem = lineItems.next();
            basketMgr.removeProductLineItem(lineItem);
        }
        
        return PIPELET_NEXT;
    }
    
    public void init()
    throws PipelineInitializationException {
        NamingMgr namingMgr = NamingMgr.getInstance();
        basketMgr = (BasketMgr)namingMgr.lookupManager(BasketMgr.REGISTRY_NAME);
    }
}